package com.valuedaas.schoolsafety.controller;

import com.valuedaas.schoolsafety.controller.user.vo.User;
import com.valuedaas.schoolsafety.util.ImageUtil;
import com.valuedaas.schoolsafety.util.WebUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 控制器帮助类
 * 
 * @author chenhua
 *
 */
public class ControllerHelper {

	private static final Logger LOG = LoggerFactory.getLogger(ControllerHelper.class);

	/**
	 * 保存上传文件
	 * 
	 * @param basePath
	 * @param relativePath
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static String saveFile(String basePath, String relativePath, MultipartFile file, String tag) throws Exception {
		if (file == null || file.isEmpty()) {
			return null;
		}
		// 保存文件
		String fileType = FilenameUtils.getExtension(file.getOriginalFilename().trim()).toLowerCase();
		String absPath = basePath + relativePath + System.currentTimeMillis() + ControllerHelper.randomStr(6, true)
				+"-" + tag +  "." + fileType;
		;
		ImageUtil.save2FileSystem(file, absPath);
		return absPath;
	}

	/**
	 * 设备连接密码的生成机制: MD5( did+"valuedaas"+reverse(did)+"valuedaas" )
	 * 
	 * @param did
	 * @return
	 */
	public static String genDeviceConnPassword(String did) {
		String salt = "valuedaas";
		String connPassword = did + salt + StringUtils.reverse(did) + salt;
		return DigestUtils.md5Hex(connPassword);
	}

	public static void main(String[] args) {
		System.out.println(ControllerHelper.genDeviceConnPassword("102163300024"));
	}

	/**
	 * 格式化错误提示信息
	 * 
	 * @param result
	 * @return
	 */
	public static List<String> errorsInfo(BindingResult result) {
		List<ObjectError> errorList = result.getAllErrors();
		List<String> rl = new ArrayList<>();
		if (errorList != null) {
			errorList.forEach(e -> rl.add(e.getDefaultMessage()));
		}
		return rl;
	}

	/**
	 * 验证所有str都不为空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String... str) {
		for (String s : str) {
			if (StringUtils.isEmpty(s)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 生成随机字符串
	 * 
	 * @author wanggq
	 * @param len
	 *            字符串长度
	 * @param isNums
	 *            是否是纯数字
	 * @return 字符串
	 */
	public static String randomStr(int len, boolean isNums) {
		String nums = "0123456789";
		String letterNums = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		if (isNums) {
			for (int i = 0; i < len; i++) {
				int num = random.nextInt(nums.length());
				sb.append(nums.charAt(num));
			}
		} else {
			for (int i = 0; i < len; i++) {
				int num = random.nextInt(letterNums.length());
				sb.append(letterNums.charAt(num));
			}
		}
		return sb.toString();
	}

	/**
	 * 写http response
	 * 
	 * @param response
	 * @param respStr
	 */
	public static void writeJsonResp(HttpServletResponse response, String respStr) {
		try {
			response.setContentLength(respStr.getBytes().length);
			response.setContentType("application/json;charset=utf-8");
			PrintWriter pw = response.getWriter();
			pw.print(respStr);
			pw.flush();
		} catch (Exception e) {
			LOG.error("exception handler", e);
		}
	}

//	list！！！
//	public static String getRoleName() {
//		// 先获取用户角色名称
//		User crtUser = WebUtil.getSessionUser();
//		String roleName = "";
//		try {
//			roleName =  crtUser.getRoles().get(0).getName();
//		} catch (Exception e) {
//			LOG.error("获取用户角色名失败", e);
//		}
//		return roleName;
//	}
//

}
